import { Canvas, View, Text } from "@tarojs/components"
import Taro from "@tarojs/taro";
import React, { useEffect, useState } from "react";
import uCharts from '@qiun/ucharts';
import viewMode from "@/store/viewMode";
import http from "@/request";
import account from "@/store/account";
import moment from "moment";
import { HideLoading, ShowLoading, ShowToast, VibrateShort } from "@/utils";
import { MoneyFormat } from "@/utils/format";
import CategorySelecter from "@/components/categorySelecter";
import "./index.scss"

let selectCategoryId = null
interface monthDataType {
    balance: number,
    expense: number,
    income: number,
    month: string
}
let resData: monthDataType[] = []
let uChartsInstance: any = {};
const MonthColumnChart: React.FC<{ year: number, onSelect: (item: monthDataType) => void }> = (props) => {
    const [viewType, setViewType] = useState('expense')
    const [categoryInfo, setCategoryInfo] = useState<{
        id: number | undefined,
        name: string | undefined
    }>({
        id: undefined,
        name: undefined
    })
    const [categoryVisible, setCategoryVisible] = useState(false)

    const switchCategoryVisible = (val) => {
        viewMode.setCategoryVisible(val)
        setCategoryVisible(val)
    }

    const queryData = () => {
        const startDate = `${props.year}-01-01`
        ShowLoading()
        const params = {
            startDate,
            endDate: moment(startDate).endOf('year').format('YYYY-MM-DD'),
            accountId: account.activeAccount?.id,
            categoryId: categoryInfo.id || undefined
        }
        http.post('/bills/statistics/month', params).then(res => {
            resData = res.data || []
            drawCharts(viewType)
            const curMon = res.data.find(item => {
                return item.month === moment().format('YYYY-MM')
            })
            if (curMon) {
                props.onSelect(curMon)
            }
            HideLoading()
        }).catch(err => {
            ShowToast(err.msg || '获取统计数据失败')
        })
    }

    const columnMoneyFormat = (num) => {
        const value = Math.abs(num)
        const mark = num >= 0 ? '' : '-'
        if (value > 10000) {
            return mark + (Math.round(value / 1000) / 10).toFixed(1) + 'w';
        }
        if (value > 1000) {
            return mark + (Math.round(value / 100) / 10).toFixed(1) + 'k';
        }
        if (value > 100) {
            return mark + Math.round(value);
        }
        return mark + (Math.round(value) === Number(value) ? value : (Math.round(value * 10) / 10).toFixed(1))
    }

    const drawCharts = (type) => {
        const categories = new Array(12).fill('').map((_, index) => {
            return index + 1
        })
        const chartDatas = categories.map(mon => {
            const monthData = resData.find(item => {
                return (moment(`${item.month}-01`).month() + 1) === mon
            })
            return monthData || {
                balance: 0,
                expense: 0,
                income: 0,
                month: `${props.year}-${mon}`
            }
        })
        const vals = chartDatas.map(item => item[type])

        const sysInfo = Taro.getWindowInfo();
        let cWidth = 700 / 750 * sysInfo.screenWidth;
        let cHeight = 350 / 750 * sysInfo.screenWidth;
        let ctx = Taro.createCanvasContext('column');
        const getMin = (list) => {
            let min = Math.min(...list)
            return Math.round(min * 2)
        }
        uChartsInstance = new uCharts({
            color: ["#f635a8", "#3c88ff"],
            padding: [15, 15, 5, 15],
            type: categoryInfo.id ? 'line' : 'column',
            context: ctx,
            width: cWidth,
            height: cHeight,
            pixelRatio: 1,
            categories,
            series: [
                {
                    name: {
                        expense: '支出',
                        income: '收入',
                        balance: '结余',
                    }[type],
                    data: vals,
                    textColor: viewMode.isNight ? '#fff' : '#25283b',
                    formatter: columnMoneyFormat
                }
            ],
            animation: true,
            legend: {
                show: false
            },
            xAxis: {
                disableGrid: true,
                itemCount: 12,
                fontColor: viewMode.isNight ? '#fff' : '#25283b'
            },
            yAxis: {
                disabled: true,
                disableGrid: true,
                data: [{ min: type === 'balance' ? getMin(vals) : 0 }]
            },
            extra: {
                column: {
                    type: "group",
                    width: 6,
                    activeBgColor: "#000000",
                    activeBgOpacity: 0.08,
                    categoryGap: 5
                }
            }
        });
    }

    const showViewType = (type) => {
        VibrateShort()
        setViewType(type)
        if (categoryInfo.id) {
            setCategoryInfo({
                id: undefined,
                name: undefined
            })
        } else {
            drawCharts(type)
        }
    }

    const onCategoryChange = (item) => {
        selectCategoryId = item.id
        if (categoryInfo.id === item.id) {
            // 没有更新
            drawCharts(viewType)
        } else {
            setCategoryInfo({
                ...categoryInfo,
                id: item.id,
                name: item.name
            })
        }
        switchCategoryVisible(false)
    }

    const onCategoryClose = () => {
        switchCategoryVisible(false)
        // 点击的选择器蒙层关闭
        if (selectCategoryId === null) {
            drawCharts(viewType)
        }
        selectCategoryId = null
    }

    const tap = (e) => {
        uChartsInstance.touchLegend(e);
        uChartsInstance.showToolTip(e, {
            formatter: (item, category, index) => {
                const data = resData.find(m => {
                    const monNum = moment(`${m.month}-01`).month()
                    return Number(monNum) === (Number(category) - 1)
                }) || {
                    balance: 0,
                    expense: 0,
                    income: 0,
                    month: `${props.year}-${category > 9 ? category : '0' + category}`
                }
                props.onSelect(data)
                return `${category}月${item.name}：${MoneyFormat(data && data[viewType])}`;
            }
        });
    }

    Taro.useDidShow(() => {
        if (resData.length) {
            // drawCharts(viewType)
        }
    })

    useEffect(() => {
        if (props.year) {
            queryData()
        }
    }, [props.year, categoryInfo.id])

    return (
        <View className="month-chart-container card-background flex-column">
            <View className="type-switch font-size28 flex-row flex-item text-main-color">
                <View onClick={() => showViewType('expense')} className={`type-item ${viewType === 'expense' ? ' active' : ''}`}>
                    <View className="type-name">支出</View>
                    <View className="bottom-line bg-contrast-color"></View>
                </View>
                <View onClick={() => showViewType('income')} className={`type-item ${viewType === 'income' ? ' active' : ''}`}>
                    <View className="type-name">收入</View>
                    <View className="bottom-line bg-contrast-color"></View>
                </View>
                <View onClick={() => showViewType('balance')} className={`type-item ${viewType === 'balance' ? ' active' : ''}`}>
                    <View className="type-name">结余</View>
                    <View className="bottom-line bg-contrast-color"></View>
                </View>
                <View className="flex1"></View>
                {
                    viewType === 'balance' ?
                        <View className="chart-title right-content">{props.year}年</View> :
                        <View onClick={() => switchCategoryVisible(true)} className="chart-title right-content flex-row flex-item">
                            {categoryInfo.name ?
                                <View className='form-input'>
                                    {categoryInfo.name}
                                </View> :
                                <View className="form-input">所有类别</View>}
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>

                }
            </View>
            {
                !categoryVisible ? <Canvas
                canvas-id="column"
                id="column"
                className="month-chart"
                onTouchEnd={tap} /> : null
            }
            
            <View className="tips font-size20 text-main-color">点击柱状图可以选中需要查看详情的月份</View>
            <CategorySelecter
            show={categoryVisible}
            value={categoryInfo.id}
            onClose={onCategoryClose}
            onSure={onCategoryChange}>
        </CategorySelecter>
        </View>
    )
}

export default MonthColumnChart